
import { getCourseSeriesList, getCourseSeriesById, addModel, updateModel, deleteModel, publishModel } from '@/api/courseseries'
import { deepClone } from "@/utils";
import { getAllTeacherList } from '@/api/user'
import { getSignature } from '@/api/upload'
import { getLevelList, addLevel, updateLevel, getLevelListByCourseId } from '@/api/level'
import { reqGetPapersList, reqPaperQueDetailByPaperId } from '@/api/paper'
// import uploadFile from '@/js/upload/uploadFile'
import TcVod from 'vod-js-sdk-v6'

const defaultModel = {
    id: '',
    ParentCSID: '',
    ParentName: '',
    title: '',
    SortNum: '',
    Description: '',
    TeacherId: '',
    LevelId: '',
    PaperIds: [],
    Attachments: [],
    CoverUrl: '',
    SubTitle: '',
    SID: '',
    MainResourceTitle: '',
    MainResourceUrl: '',
    ResSuffix: '',
    MainResourceSize: '',
    SubjectName: '',
    ApplicantCount: '',
    PlanTime: '',
    PlanStartTime: '',
    PlanEndTime: '',
    PlanStartAndEndTime: '',
    StartTime: '',
    EndTime: '',
    TeachMinute: '',
    TeachMinuteStr: '',
    IsTeach: '',
    IsTeachStr: '',
    Location: '',
    AllowCount: '',
    TeachType: '',
    IsRecommend: '',
    Body: '',
    Creater: '',
    CreateTime: '',
    ShowCoverUrl: ''
}

export default {

    data() {
        function getSignature() {
            console.log("out")
            return getSignature().then(function (response) {
                console.log('response', response)
                return response.data.Signature
            })
        }

        return {
            viewModel: {
                page: 1,
                pageSize: 10,
                total: 0,
                Title: '',
                OrderBy: 'ID',//排序字段
                IsAsc: '' //是否升序
            },
            dialogPaperVisible: false,
            dialogPaperType: '',
            viewPaperVisible: false,
            clickPaperTitle: "",
            subPaperTitle: "",
            minSubPaperTitle: "",
            paperData: [],
            fixedPaperData: [],
            defaultProps: {
                children: "children",
                label: "label"
            },
            courseModel: Object.assign({}, defaultModel),
            model: Object.assign({}, defaultModel),
            innerModel: { ParentTitle: '', LevelTitle: '', Id: '', ParentId: '', SortNum: 0 },
            innerCourseModel: { ParentTitle: '', LevelTitle: '', Id: '', ParentId: '', SortNum: 0 },
            modelList: [],
            teacherList: [],
            levelList: [],
            courseLevelList: [],
            paperList: [],
            innerVisible: false,
            innerCourseVisible: false,
            oprateLevelVisible: false,
            dialogLevelType: '',
            dialogCourseLevelType: '',
            multipleSelection: [],
            teacheTypeList: ["直播", "录播"],
            loading: false,
            apiPre: process.env.VUE_APP_BASE_API,
            actionUrl: '',
            mainActionUrl: '',
            courserules: {
                title: [{ required: true, message: "请输入课程体系名称", trigger: "blur" }],
                SubTitle: [{ required: true, message: "请输入课程体系简介", trigger: "blur" }],
                CoverUrl: [{ required: true, message: "请上传课程体系图片", trigger: "change" }]
            },
            rules: {
                title: [{ required: true, message: "请输入章节名称", trigger: "blur" }],
                SubTitle: [{ required: true, message: "请输入简介", trigger: "blur" }],
                LevelId: [{ required: true, message: "请选择等级", trigger: "change" }],
                PlanTime: [{ required: true, message: "请输入开始/结束时间", trigger: "blur" }],
                CoverUrl: [{ required: true, message: "请上传封面", trigger: "change" }],
                // TeacherId: [{ required: true, message: "请选择讲师", trigger: "blur" }],
                TeachType: [{ required: true, message: "请选择教学类型", trigger: "blur" }]
            },
            innerRules: {
                LevelTitle: [{ required: true, message: "请输入等级名称", trigger: "blur" }],
            },
            id: '',
            active: 0,
            activeStr: '创建课程',
            tcVod: '',
            uploaderInfos: []
        }
    },
    computed: { // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存

    },
    created() {  // 实例创建完成后执行的代码
        this.id = this.$route.params && this.$route.params.id
        // this.id = '97fabc70-dd66-490f-92a2-016be74a1fdc'
        this.getList(this.id)
        this.actionUrl = this.apiPre + '/Upload/UploadAttachment'
        this.mainActionUrl = this.apiPre + '/Upload/UploadAttachment'
        this.init()
    },
    methods: {
        async getList(id) {
            const res = await getCourseSeriesById(id);
            if (res.data) {
                this.modelList = res.data;
                if (this.modelList && this.modelList.length > 0)
                    this.activeStr = '编辑课程'
                this.courseModel = deepClone(this.modelList[0])
            }
        },
        init() {
            this.tcVod = new TcVod({
                getSignature: getSignature
            })
        },
        uploadvideo(file) {
            var mediaFile = file
            var progressLabelElement = this.$refs.progressLabel
            const uploader = this.tcVod.upload({
                mediaFile: mediaFile, // 媒体文件（视频或音频或图片），类型为 File
            })

            uploader.on('media_progress', function (info) {
                console.log('info.percent', info.percent) // 进度
            })

            var fileIdElement = this.$refs.fileId
            var videourlElement = this.$refs.videourl
            var videoaddressElement = this.$refs.videoaddress


            uploader.done().then(function (doneResult) {
                // deal with doneResult
                console.log('doneResult', doneResult)
                fileIdElement.name = doneResult.fileId
                videourlElement.name = doneResult.video.url
                videoaddressElement.value = doneResult.video.url

            }).catch(function (err) {
                // deal with error
            })
        },
        async confirmCourseModel() {
            //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
            var v;
            this.$refs['courseModel'].validate(valid => {
                v = valid;
            });
            if (!v) {
                return false;
            }
            if (this.id == '0') {
                var m = await addModel(this.courseModel)
                this.id = m.data.ID
                this.courseModel = Object.assign({}, m.data)
            } else {
                var m = await updateModel(this.courseModel)
                this.id = m.data.ID
                this.courseModel = Object.assign({}, m.data)
            }

            this.getList(this.id)
            this.active = 1
            this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
                duration: 3000
            });
        },
        async getAllTeacherList() {
            const res = await getAllTeacherList();
            if (res.data) {
                this.teacherList = res.data;
            }
        },
        async reqGetPapersList() {
            const res = await reqGetPapersList();
            if (res.data) {
                this.paperList = res.data.papersList;
            }
        },
        async getLevelList() {
            const res = await getLevelListByCourseId(this.id);
            if (res.data) {
                this.levelList = res.data;
            }
        },
        async confirmModel() {
            //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
            var v;
            this.$refs['model'].validate(valid => {
                v = valid;
            });
            if (!v) {
                return false;
            }
            debugger
            const isEdit = this.dialogType === 'edit';

            var fileIdElement = this.$refs.fileId
            var videourlElement = this.$refs.videourl
            if (fileIdElement.name) {
                this.model.FileId = fileIdElement.name
                this.model.ResDownloadUrl = videourlElement.name
                this.model.ResPlayUrl = videourlElement.name
                this.model.ResPreviewUrl = videourlElement.name
                this.model.ResStoreUrl = videourlElement.name
                this.model.MainResourceUrl = videourlElement.name
            }
            console.log('this.model', this.model)
            debugger
            if (isEdit) {
                var res = await updateModel(this.model)
                console.log('res', res)
            } else {
                var res = await addModel(this.model)
                console.log('res', res)
            }
            this.model = Object.assign({}, defaultModel)
            this.getList(this.id)
            this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
                duration: 3000
            });
        },
        handleCourseAvatarSuccess(res, file) {//图片上传成功响应方法
            this.courseModel.CoverUrl = res.data.DownloadUrl;
        },
        beforeCourseAvatarUpload(file) {
            const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 4;

            if (!isImg) {
                this.$notify({
                    title: "失败",
                    message: "上传图片只能是 JPG/JPEG/PNG 格式!",
                    type: "error",
                    duration: 3000
                });
                return false
            }
            if (!isLt2M) {
                this.$notify({
                    title: "失败",
                    message: "上传图片大小不能超过 4MB!",
                    type: "error",
                    duration: 3000
                });
                return false
            }
            return isImg && isLt2M;
        },
        reset() {
            this.$confirm("确认重置?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    this.model = Object.assign({}, defaultModel)
                    this.$refs['model'].clearValidate()
                })
                .catch(err => {
                    console.error(err);
                });
        },
        resetCourse() {
            this.$confirm("确认重置?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    this.courseModel = Object.assign({}, defaultModel)
                    this.$refs['courseModel'].clearValidate()
                })
                .catch(err => {
                    console.error(err);
                });
        },
        handleEdit(scope) {
            this.dialogType = 'edit';
            this.model = deepClone(scope.row);
            if (this.model.LevelId == '00000000-0000-0000-0000-000000000000')
                this.model.LevelId = ''
            if (this.model.TeacherId == '00000000-0000-0000-0000-000000000000')
                this.model.TeacherId = ''
            this.$nextTick(() => {
                this.$refs['model'].clearValidate() //清空上次的错误验证提示
            });
        },
        handleAdd(scope) {
            this.$nextTick(() => {
                var timestamp = new Date().getTime();
                var n = 0
                if (scope.row.children)
                    n = scope.row.children.length + 1
                else
                    scope.row.children = []
                var newChild = { id: 'id' + timestamp, title: '节点' + n, children: [] };
                this.model = deepClone(defaultModel)
                this.model.ParentName = scope.row.title
                this.model.title = newChild.title
                this.model.ParentCSID = scope.row.id
                scope.row.children.push(newChild);
                this.$refs['model'].clearValidate() //清空上次的错误验证提示
            })
            this.dialogType = 'new';
        },
        handleDelete(scope) {
            if (scope.row.children && scope.row.children.length > 0) {
                this.$notify({
                    title: "提示",
                    message: "请先删除下面的子节点!",
                    type: "warning",
                    duration: 3000
                });
                return false
            }
            if (scope.row.id.indexOf('id') > -1) {
                this.getList(this.id)
                this.model = deepClone(defaultModel)
                this.$notify({
                    title: "成功",
                    message: "操作成功",
                    type: "success",
                    duration: 3000
                });
                return false
            }
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    await deleteModel(scope.row.id);
                    this.$notify({
                        title: "成功",
                        message: "操作成功",
                        type: "success",
                        duration: 3000
                    });
                    this.getList(this.id)
                })
                .catch(err => {
                    console.error(err);
                });
        },
        choosePaper(rows) {//选择试卷
            this.dialogPaperVisible = true;
            this.$nextTick(() => {
                this.toggleSelection(rows) //选中已关联的试卷
            });
        },
        viewPaper(scope) {//预览试卷
            this.viewPaperVisible = true
            this.seePaperDetail(scope.row)
        },
        async seePaperDetail(row) {
            let result = await reqPaperQueDetailByPaperId(row.paper_id);
            let singleData = result.data.singleData;
            let multipleData = result.data.multipleData;
            let judgeData = result.data.judgeData;
            let fillData = result.data.fillData;
            //初始化数据
            // this.filterText = "";
            this.clickPaperTitle = `试卷详情：${row.paper_name}`;
            this.subPaperTitle = `试卷总分：${
                result.data.total_score
                }分，试卷总题数：${result.data.total_num}道。`;
            this.minSubPaperTitle = `单选题${result.data.single_num}道（每道${
                result.data.paper.single_score
                }分），
    多选题${result.data.multiple_num}道（每道${
                result.data.paper.multiple_score
                }分），
    判断题${result.data.judge_num}道（每道${
                result.data.paper.judge_score
                }分），
    填空题${result.data.fill_num}道（每道${
                result.data.paper.fill_score
                }分）。`;
            this.paperData = [
                {
                    id: 1,
                    label: "单选题列表",
                    children: singleData
                },
                {
                    id: 2,
                    label: "多选题列表",
                    children: multipleData
                },
                {
                    id: 3,
                    label: "判断题列表",
                    children: judgeData
                },
                {
                    id: 4,
                    label: "填空题列表",
                    children: fillData
                }
            ];
        },
        confirmPaper() {//保存选中的试卷
            // this.model.PaperIds = this.multipleSelection
            this.innerCourseModel.PaperIds = this.multipleSelection
            this.dialogPaperVisible = false
        },
        toggleSelection(rows) {
            this.$refs.multipleTable.clearSelection();
            if (rows) {
                rows.forEach(row => {
                    var p = this.paperList.filter(p => p.paper_id == row.paper_id)[0]
                    this.$refs.multipleTable.toggleRowSelection(p, true);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        // 封面维护等级
        oprateCourseLevel() {
            this.innerCourseVisible = true;
        },
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        getNodeData(data) {
            this.dialogCourseLevelType = 'edit';
            this.innerCourseModel = {
                ParentTitle: data.parentTitle, ParentId: data.parentId,
                LevelTitle: data.label, Id: data.value, SortNum: data.SortNum,
                PaperIds: data.PaperIds
            }
            this.$refs['innerCourseModel'].clearValidate()
        },
        addCourseLevel() {
            this.dialogCourseLevelType = 'new';
            if (this.innerCourseModel.Id == '') {
                this.$notify({
                    title: "提示",
                    message: "请选择等级",
                    type: "warning",
                    duration: 3000
                });
                return false
            }
            this.innerCourseModel = { ParentTitle: this.innerCourseModel.LevelTitle, ParentId: this.innerCourseModel.Id, LevelTitle: '', Id: '', SortNum: 0, PaperIds: [] }
        },
        addFirstCourseLevel() {
            this.dialogCourseLevelType = 'new';
            this.innerCourseModel = { ParentTitle: '/', ParentId: '', LevelTitle: '', Id: '', SortNum: 0, PaperIds: [] }
        },
        async confirmCourseLevel() {
            var v;
            this.$refs['innerCourseModel'].validate(valid => {
                v = valid;
            });
            if (!v) {
                return false;
            }
            const isEdit = this.dialogCourseLevelType === 'edit';

            if (isEdit) {
                await updateLevel(this.innerCourseModel);
            } else {
                await addLevel(this.innerCourseModel)
            }
            this.getLevelList()
            this.innerCourseModel = { ParentTitle: '', ParentId: '', LevelTitle: '', Id: '', SortNum: 0, PaperIds: [] }
            this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
                duration: 3000
            });
        },
        handleAvatarSuccess(res, file) {//图片上传成功响应方法
            debugger
            this.model.CoverUrl = res.data.SaveUrl;
            this.model.ShowCoverUrl = res.data.DownloadUrl;
        },
        beforeAvatarUpload(file) {
            const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 4;

            if (!isImg) {
                this.$notify({
                    title: "失败",
                    message: "上传图片只能是 JPG/JPEG/PNG 格式!",
                    type: "error",
                    duration: 3000
                });
                return false
            }
            if (!isLt2M) {
                this.$notify({
                    title: "失败",
                    message: "上传图片大小不能超过 4MB!",
                    type: "error",
                    duration: 3000
                });
                return false
            }
            return isImg && isLt2M;
        },
        handleAttachSuccess(res, file) {//图片上传成功响应方法
            var fs = res.data.split('/');
            var fn = fs[fs.length - 1]
            var m = this.model.Attachments[this.model.Attachments.length - 1]
            m.AttachmentUrl = res.data
            m.AttachmentDIsplayName = fn
            this.model.Attachments.splice(this.model.Attachments.length - 1, 1, m)
        },
        beforeAttachUpload(file) {
            this.model.Attachments.push({ AttachmentDIsplayName: file.name, AttachmentSize: parseFloat(file.size / 1024).toFixed(2), AttachmentSizeStr: parseFloat(file.size / 1024).toFixed(2) + "KB" })
        },
        handleMainSuccess(res, file) {//资源上传成功响应方法
            this.model.MainResourceUrl = res.data
            this.$notify({
                title: "成功",
                message: "上传成功!",
                type: "success",
                duration: 3000
            });
        },
        beforeMainUpload(file) {

            var fileName = file.name || ''
            var ext = fileName.split('.')[fileName.split('.').length - 1]
            this.model.MainResourceTitle = file.name
            this.model.ResSuffix = ext
            this.model.MainResourceSize = parseInt(file.size / 1024)

            this.uploadvideo(file);

            return false;
            var fileName = file.name || ''
            var ext = fileName.split('.')[fileName.split('.').length - 1]
            if (ext !== "doc" && ext !== "docx" && ext !== "xls" && ext !== "xlsx"
                && ext !== "ppt" && ext !== "pptx" && ext !== "pdf" && ext !== "mp4") {
                this.$notify({
                    title: "失败",
                    message: "上传资源只能是 doc/docx/xls/xlsx/ppt/pptx/pdf/mp4 格式!",
                    type: "error",
                    duration: 3000
                });
                return false
            }
            // ppt(10MB)，word(10MB)，excel(5MB)
            if (ext == "doc" || ext == "docx" || ext == "ppt" || ext == "pptx") {
                debugger
                if (parseInt(file.size) > parseInt('10485760‬')) {
                    this.$notify({
                        title: "失败",
                        message: "上传word、ppt文件上限为10MB!",
                        type: "error",
                        duration: 3000
                    });
                    return false
                }
            }

            if (ext == "xlsx" || ext == "xls") {
                if (parseInt(file.size) > parseInt('5242880')) {
                    this.$notify({
                        title: "失败",
                        message: "上传excel文件上限为5MB!",
                        type: "error",
                        duration: 3000
                    });
                    return false
                }
            }

            this.model.MainResourceTitle = file.name
            this.model.ResSuffix = ext
            this.model.MainResourceSize = parseInt(file.size / 1024)
        },
        removeAttach(scope) {
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    this.model.Attachments.splice(this.model.Attachments.indexOf(scope.row), 1)
                    this.$notify({
                        title: "成功",
                        message: "操作成功",
                        type: "success",
                        duration: 3000
                    });
                })
                .catch(err => {
                    console.error(err);
                });
        },
        goPublish() {
            if (this.modelList[0].children && this.modelList[0].children.length > 0) {
                var m = this.modelList[0].children[0]
                this.model = deepClone(m);
            }
            this.courseModel = deepClone(this.modelList[0])
            this.active = 2
        },
        goBack() { //从预览发布页面回到维护教材内容页面
            this.active = 1
        },
        publishCourse() {
            this.$confirm("确认发布?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    await publishModel(this.courseModel.id);
                    this.$notify({
                        title: "成功",
                        message: "操作成功",
                        type: "success",
                        duration: 3000
                    });
                })
                .catch(err => {
                    console.error(err);
                });
        }
    }
}